function minSailCost(input) {
  let m = input.length;
  let n = input[0].length;
  const dp = new Array(m).fill(0).map(() => new Array(n).fill(0));
  for (let i = 1; i < m && input[i][0] !== 2; i++) {
    if (input[i][0] === 0) {
      dp[i][0] = dp[i - 1][0] + 2;
    }
    if (input[i][0] === 1) {
      dp[i][0] = dp[i - 1][0] + 1;
    }
  }
  for (let j = 1; j < n && input[0][j] !== 2; j++) {
    if (input[0][j] === 0) {
      dp[0][j] = dp[0][j - 1] + 2;
    }
    if (input[0][j] === 1) {
      dp[0][j] = dp[0][j - 1] + 1;
    }
  }
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (input[i][j] === 0) {
        if (!dp[i - 1][j] && dp[i][j - 1]) {
          dp[i][j] = dp[i][j - 1] + 2;
        } else if (dp[i - 1][j] && !dp[i][j - 1]) {
          dp[i][j] = dp[i - 1][j] + 2;
        } else if (dp[i - 1][j] && dp[i][j - 1]) {
          dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 2;
        }
      }
      if (input[i][j] === 1) {
        if (!dp[i - 1][j] && dp[i][j - 1]) {
          dp[i][j] = dp[i][j - 1] + 1;
        } else if (dp[i - 1][j] && !dp[i][j - 1]) {
          dp[i][j] = dp[i - 1][j] + 1;
        } else if (dp[i - 1][j] && dp[i][j - 1]) {
          dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1;
        }
      }
    }
  }
  return dp[m - 1][n - 1];
}


const input = [[1, 1, 1, 1, 0], [0, 1, 0, 1, 0], [1, 1, 2, 1, 1], [0, 2, 0, 0, 1]]
console.log(minSailCost(input));